package com.speedydial;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.speedydial.persistence.MessageDbAdapter;

public class EditSMSForm extends Activity {
	
	private static final String TAG = "EditSMSForm";
	
	/** Instancia de la base de datos para guardar los diferentes
	 * contactos
	 *  */
	private MessageDbAdapter messageDbAdapter;
	
	private EditText title;
	private EditText body;
	private EditText telephone;
	
	private Long mRowId;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // intentamos iniciar las bbdd
        messageDbAdapter = new MessageDbAdapter(this);
        messageDbAdapter.open();
        
        // set the view
        setContentView(R.layout.edit_sms_form);
        
        // set the properties for the form elements
        title = (EditText) findViewById(R.id.editTitle);
        body = (EditText) findViewById(R.id.editBody);
        telephone = (EditText)findViewById(R.id.editTelephone);
        
        Button saveBtn = (Button) findViewById(R.id.save);
        
        // check out the content
        mRowId = (savedInstanceState == null) ? null :
        	(Long)savedInstanceState.getSerializable(messageDbAdapter.KEY_ROWID);
        
        // continue if mRowId
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(messageDbAdapter.KEY_ROWID)
                                    : null;
        }
        
        // fill the form 
        populateForm();
        
        // add listener for button
        saveBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
               
                setResult(RESULT_OK);
                finish();
            }
          
        });
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	populateForm();
    }
  
    @Override
    protected void onStop() {
    	super.onStop();
    	saveState();
    } 


	private void initList() {

	}
    
	/**
	 * Rellena el formulario basado en que el rowID se haya rellenado
	 */
	private void populateForm(){
		
		if( mRowId == null ){
			return;
		}
		
		// else to the cursor fetching
		Cursor contact = messageDbAdapter.fetchNote(mRowId);
		startManagingCursor(contact);
		
		int intTitle = contact.getColumnIndexOrThrow(messageDbAdapter.KEY_TITLE);
		int intBody = contact.getColumnIndexOrThrow(messageDbAdapter.KEY_BODY);
		int tel = contact.getColumnIndexOrThrow(messageDbAdapter.KEY_TELEFONO);
		
		title.setText(contact.getString(intTitle));
		body.setText( contact.getString(intBody));
		telephone.setText( contact.getString(tel));
		
	}
	
	/**
	 * punto central para guardar todo en caso de que haya algun cambio
	 * dentro del app/Activity
	 */
	private void saveState() {
		
		Log.v(TAG, "saving");
		
		String strTitle = title.getText().toString();
		String strBody = body.getText().toString();
		String tele = telephone.getText().toString();
		
		// now save it
		if (mRowId == null) {
            long id = messageDbAdapter.createSMSDestinatary(strTitle, strBody, tele);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            messageDbAdapter.updateNote(mRowId, strTitle, strBody, null, tele);
        }
	}
	
	@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(messageDbAdapter.KEY_ROWID, mRowId);
    }
	
	@Override
    protected void onPause() {
        super.onPause();
        saveState();
    }
}
